import md5 from './md5'
let that = this;
const API_BASE_URL = 'http://slp1.slzrsz.com:8888' // 域名
const apiurl = [] //不打印的url
const APPID = 'slzrweapp'
const APPTYPE = 'WEAPP'
const APPKEY = 'A0E6C376000F44AEF13F58614C379DD9'
let nonce = getNonce(10);
let timeStamp = getTimeStamp();


/**
 * set  不传或true时,page.data中生成url请求名的变量存数据;为字符串时,page.data中生成该字符串为名的变量存数据
 */
const request = (method, url, data, set) => {
  let userinfo = wx.getStorageSync("USERLOGIN"), token = userinfo == '' ? '' : userinfo.Token;
  let _url = /http/.test(url) ? url : API_BASE_URL + url
  let signStr = "AppId=" + APPID + "&AppKey=" + APPKEY + "&AppType=" + APPTYPE + "&Data=" + encodeURIComponent(JSON.stringify(data)) + "&Nonce=" + nonce + "&TimeStamp=" + timeStamp + "&Url=" + _url;
  let sign = md5.hex_md5(signStr).toLocaleUpperCase();
  let promise = new Promise((res, err) => {
    wx.request({
      url: _url,
      method: method,
      data: {
        "AppType": APPTYPE,
        "AppId": APPID,
        "Nonce": nonce,
        "TimeStamp": timeStamp,
        "Signature": sign,
        "Data": data,
        "Url": _url,
        "SignType": "MD5",
        "SignVersion": "1.1"
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'bearer ' + token
      },
      success:function(e){
        res(e.data);
      },
      fail:function(e){
        err(e);
      }
    })
  })
  promise.then(res => {
    console.log("调用接口：url:  "+url+"     success")
    console.log("         data:",data);
    console.log("         res:",res.Data);
    // if (url == "/common/send_sms") return;
    if (res.Code == 0) {
      if (typeof set == 'undefined' || set === true) {
        let index = url.lastIndexOf("/")
        let urltemp = index > -1 ? url.substring(index + 1) : url;
        let page = getCurrentPages()
        page[page.length - 1].setData({
          [urltemp]: res.data
        })
      } else if (set) {
        page[page.length - 1].setData({
          [set]: res.data
        })

      }
    }
    if (url == "/finish_tack") return; //code非0时不反应的url
    if (res.Code != 0) {
      wx.showToast({
        title: res.Message,
        icon: "none",
        duration: 4000
      })
    }
  }).catch(err => {
    let msg;
    console.log("调用接口：url:  "+url+"     catcherror")
    if (err.errMsg.match('timeout')) {
      msg = "后台请求数据超时"
    } else {
      msg = err.errMsg
    }
    wx.showToast({
      title: msg,
      icon: "none",
      duration: 4000
    });
    console.log(err, url + "     err")
  })
  return promise;
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

function getTimeStamp() {
  var tmp = Date.parse(new Date()) + '';
  return tmp.substr(0, 10);
}
function getDate(date, fmt) {
  date = date || new Date();

  if(typeof(date) === 'string') date = new Date(date.replace(new RegExp('-','g'), '/'));
  var o = {
    "M+": date.getMonth() + 1,                 //月份   
    "d+": date.getDate(),                    //日   
    "h+": date.getHours(),                   //小时   
    "m+": date.getMinutes(),                 //分   
    "s+": date.getSeconds(),                 //秒   
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
    "S": date.getMilliseconds()             //毫秒   
  };
  if(!!!fmt)  fmt = 'yyyy-MM-dd hh:mm:ss';
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    
  return fmt;
}
function getNonce(min, max) {
  var str = "",
    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

  // 随机产生
  var range = max != undefined ? Math.round(Math.random() * (max - min + 1)) + min : min;
  let pos = 0;
  for (var i = 0; i < range; i++) {
    pos = Math.round(Math.random() * (arr.length - 1));

    str += arr[pos];
  }
  return str;
}
function str2Date(s) {
  if(s.length == 8) // yyyyMMdd
    return new Date(s.substr(0,4) + '/' + s.substr(4,2) + "/" + s.substr(6,2));
  s = s.replace(/-/g,"/");
  s = s.replace(/(\.\d+)?/g,"");
  var date = new Date(s);
  return date;
 }
//////////////////////
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/* const check = (value, type, text) => {
  let reg;
  if (type == "phone") {
    reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})))+\d{8}$/
  } else if (type == "name") {
    reg = /^[\u4E00-\u9FA5]{2,4}$/
  } else console.error("请使用正确类型")
  if (typeof value != "string") value = String(value);
  let out = value.match(reg);
  // console.log(out, value, reg)
  if (out) {
    return out[0];
  } else {
    wx.showToast({
      title: text,
      icon: "none",
      duration: 3000
    })
  }
} */

/**
 *  if (app.check([
        [true, 0, "支付金额不能为0"]
    ])) return;
 */
const check = (arr) => {
  for (let item of arr) {
    let reg;
    if (item[1] == "phone") {
      reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})))+\d{8}$/
    } else if (item[1] == "name") {
      reg = /^[\u4E00-\u9FA5]{2,4}$/
    } else if (item[1] == "number") {
      reg = /^(0|([1-9]\d*))(\.\d+)?$/
    } else if (item[1] == "nospace") {
      reg = /\S+/
    } else if (item[1] instanceof RegExp) {
      reg = item[1]
    } else if (typeof item[0] == "boolean") { } else console.error("请使用正确类型")
    if (typeof item[0] == "boolean") {
      // console.log(item[0],typeof item[0],item[2],"uuu")
      if (!item[0]) {
        wx.showToast({
          title: item[2],
          icon: "none",
          duration: 3000
        });
        return true;
      } /* else {
        return false;
      } */
    } else if (typeof item[0] != "string")
      item[0] = String(item[0]);
    else if (!reg.test(item[0])) {
      wx.showToast({
        title: item[2],
        icon: "none",
        duration: 3000
      });
      return true;
    }
  }
  return false;
}
const getToken = function (t, data) {
  data = data || false;
  let token = wx.getStorageSync("token")
  if (!token) {
    /* wx.getSetting({
        success: res => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo;
                wx.login({
                  success: res2 => {
                    //res.code
                    request('post', "/common/login", {
                      code: res2.code,
                      nickname: res.userInfo.nickName,
                      head_pic: res.userInfo.avatarUrl
                    }).then(res3 => {
                      if (res3.code == 0) {
                        wx.setStorageSync("token", res3.data.user_token);
                      } else if (res3.code = 100) {
                        //需要手机号
                      }
                    });
                  }
                })
              }
            })
          } else {
          	
          }
        }
      }); */
    if (/\/pages\//.test(data)) {
      wx.navigateTo({
        url: data
      })
    } else if (data) {
      t.setData({
        [data]: true
      })
    } else {
      /*       wx.navigateTo({
              url: "pages/login/login"
            }) */
    }

  }
  return token;
}
const wxSaveImage = function (key) {
  return function () {
    var t = this;
    wx.getSetting({
      success: res => {
        let str = res.authSetting['scope.writePhotosAlbum'];
        if (str || typeof str == "undefined") {
          wx.showLoading({
            title: '保存中...',
            mask: true,
          });
          wx.downloadFile({
            url: t.data[key],
            success: function (res) {
              if (res.statusCode === 200) {
                let img = res.tempFilePath;
                wx.saveImageToPhotosAlbum({
                  filePath: img,
                  success(res) {
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success',
                      duration: 2000
                    });
                  },
                  fail(err) {
                    let msg = '保存失败';
                    if (/cancel/.test(err.errMsg)) {
                      msg = '取消保存'
                    }
                    wx.showToast({
                      title: msg,
                      icon: 'none',
                      duration: 2000
                    });
                  }
                });
              }
            },
            complete: function () {
              wx.hideLoading();
            }
          });
        } else if (str === false) {
          wx.showModal({
            title: "需要授权才能保持图片",
            showCancel: false,
            success: function () {
              wx.openSetting({
                success(res) {
                  if (res.authSetting['scope.writePhotosAlbum']) {
                    console.log("ok")
                  } else {
                    wx.showToast({
                      title: '您没有授权，无法保存到相册',
                      icon: 'none'
                    })
                  }
                }
              })

            }
          })
        }
      }
    })
  }

}
const debounce = function (fn, delay) {
  return;
  var timer;
  return function () {
    var _this = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    if (!timer) {
      fn.apply(_this, args);
    }
    timer = setTimeout(function () {
      timer = null;
    }, delay);
  };
}
const setTempStorage = function (key, value, num) {
  var time = Date.parse(new Date()),
    time2 = time + num;
  wx.setStorageSync(key, value);
  wx.setStorageSync(key + '_temp', time2);
}
const getTempStorage = function (key, callback) {
  var time = Date.parse(new Date());
  var time2 = wx.getStorageSync(key + '_temp');
  var output = wx.getStorageSync(key);
  if (key && time2 > time) {
    return output
  } else {
    return callback ? callback() : '';
  }
}
const wxNaviback = function (url) {
  let arr = getCurrentPages(),
    delta;
  for (let k in arr) {
    if (arr[k].route == url) {
      delta = arr.length - 1 - k;
      break;
    }
  }
  if (delta) {
    wx.navigateBack({
      delta: delta
    });
  } else {
    wx.reLaunch({
      url: url
    })
  }
}
/* const wxWebsocket = function() {
  let url = "ws://47.112.119.16:20828"
  var socket = wx.connectSocket({
    url: url,
    // data: data,
    method: 'post',
    success: res => {
      console.log('WebSocket connect', res);
    },
    fail: err => {
      console.log('出现错误啦！！' + err);
      wx.showToast({
        title: '网络异常！',
      })
    }
  })
  socket.onOpen(res => {
    console.log(res, "onopen")
  });
  socket.onClose(err => {
    console.log(err, "onclose")
  });
  socket.reopen = function () {
    this=wx.connectSocket({
      url: url,
      // data: data,
      method: 'post',
      success: res => {
        console.log('WebSocket connect', res);
      },
      fail: err => {
        console.log('出现错误啦！！' + err);
        wx.showToast({
          title: '网络异常！',
        })
      }
    })
  }

  socket.onMessage(res => {
    console.log(res,"jjjjjjjjjjjjjjjj")
    if (res.type == 2) {
      console.log("type=2,充电结束")
    } else if (res.type == 3) {
      console.log("type=3,停止充电成功")
    }
  });
  
  // socket.send();
  // socket.close(); 
  return socket;
} */
const wxWebsocket = function (t, id) {
  if (!id) return;
  // t=this;
  function reconnect() {
    if (t.lockReconnect) return;
    t.lockReconnect = true;
    clearTimeout(t.timer)
    if (typeof t.globalData.limit == "undefined") t.globalData.limit = 0
    if (t.globalData.limit < 12) {
      t.timer = setTimeout(() => {
        connect();
        t.lockReconnect = false;
      }, 5000);
      t.globalData.limit = t.globalData.limit + 1;
    }
  };

  function connect() {
    console.log(new Date())
    wx.connectSocket({
      url: 'wss://socket.yichongbaokeji.cn:20828',
      success: function (res) {
        console.log(res, "open")
        initListener();
      },
      fail: function (err) {
        console.log(err, "connet fail")
      }
    })
  }
  connect();
  function initListener() {
    console.log("id", id)
    wx.onSocketClose(function (res) {
      console.log(res, "onclose")
      t.globalData.socketOpen = false;
      reconnect();
    })
    wx.onError((error) => {
      console.log(error, "onError")
      reconnect();
    })
    wx.onSocketOpen(function (res) {
      console.log(res, "onopen")
      t.globalData.socketOpen = true;
      wx.sendSocketMessage({
        data: JSON.stringify({
          user_id: id
        }),
      })
    })
    wx.onSocketMessage(function (res) {
      console.log(JSON.parse(res.data), "getmessage")
      res = JSON.parse(res.data);
      switch (res.type) {
        case 1:
          console.log("登录成功", res)
          // t.globalData.isSocketLogin=true
          break;
        case 2:
          console.log("充电结束", res)
          /*           wx.hideLoading({
                      success: (res) => {},
                    }) */
          wx.showModal({
            title: '',
            content: '充电结束',
            showCancel: false
          })
          // if (t.globalData.chargeEnd) t.globalData.chargeEnd(); else console.log(2, "no function")
          break;
        case 3:
          console.log("停止成功", res)
          wx.showToast({
            title: '停止成功',
          })
          // if(t.globalData.stopCharge) t.globalData.stopCharge(); else console.log(3,"no function")
          break;
        case 4:
          console.log("启动失败")
          if (t.globalData.chargeinit) {
            t.globalData.chargeinit(2, res.msg)
            t.globalData.chargeinit = null;
          } else {
            t.globalData.chargeinit = [2, res.msg];
          }
          break;
        case 5:
          console.log("启动成功")
          if (t.globalData.chargeinit) {
            t.globalData.chargeinit(1);
            t.globalData.chargeinit = null;
          } else {
            t.globalData.chargeinit = [1, 0];
          }
          break;
        case 6:
          console.log("充电异常", res)
          if (typeof t.globalData.chargeerror == "function") {
            t.globalData.chargeerror(res.msg);
            t.globalData.chargeerror = null;
          } else {
            t.globalData.chargeerror = "type6"
          }
      }
    })
  }

}
module.exports = {
  formatTime,
  debounce,
  getDate,
  getNonce,
  getTimeStamp,
  str2Date,
  check,
  getToken,
  wxSaveImage,
  wxNaviback,
  wxWebsocket,
  request,
  setTempStorage,
  getTempStorage,
  get: (url, data, set) => request('get', url, data, set),
  post: (url, data, set) => request('post', url, data, set),
}